<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据库数据模糊匹配示例</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <style>
        .search-container {
            position: relative;
            width: 100%;
            max-width: 500px;
            margin: 20px auto;
        }

        .search-input {
            width: 100%;
            padding: 12px 12px 12px 40px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }

        .search-input:focus {
            outline: none;
            border-color: #4299e1;
            box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.1);
        }

        .search-icon {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #999;
        }

        .loading-icon {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #999;
            display: none;
        }

        .suggestions-list {
            position: absolute;
            left: 0;
            right: 0;
            top: 100%;
            margin: 0;
            padding: 0;
            list-style: none;
            background: white;
            border: 1px solid #ddd;
            border-radius: 0 0 8px 8px;
            max-height: 250px;
            overflow-y: auto;
            z-index: 1000;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            display: none;
        }

        .suggestion-item {
            padding: 12px 16px;
            cursor: pointer;
            transition: background-color 0.15s;
        }

        .suggestion-item:hover, .suggestion-item.active {
            background-color: #edf2f7;
        }

        .highlight {
            color: #2b6cb0;
            font-weight: 600;
        }

        .no-results {
            padding: 12px 16px;
            color: #718096;
        }

        .error-message {
            padding: 12px 16px;
            color: #e53e3e;
        }

        .debug-info {
            max-width: 500px;
            margin: 20px auto;
            padding: 10px;
            border: 1px solid #eee;
            border-radius: 4px;
            font-size: 14px;
            color: #666;
        }
    </style>
</head>
<body>
<div class="container">
    <h1 style="text-align: center; margin-top: 50px; color: #2d3748;">数据库搜索模糊匹配</h1>

    <div class="search-container">
        <i class="fa fa-search search-icon"></i>
        <input
                type="text"
                id="searchInput"
                class="search-input"
                placeholder="输入关键词搜索..."
                autocomplete="off"
        >
        <i class="fa fa-spinner fa-spin loading-icon" id="loadingIcon"></i>
        <ul id="suggestions" class="suggestions-list"></ul>
    </div>

    <div class="debug-info" id="debugInfo">
        状态: 等待输入...
    </div>
</div>

<script>
    $(document).ready(function() {
        // DOM元素
        const $searchInput = $('#searchInput');
        const $suggestionsList = $('#suggestions');
        const $loadingIcon = $('#loadingIcon');
        const $debugInfo = $('#debugInfo');
        let currentIndex = -1;
        let lastRequest = null;

        // 输入事件处理
        $searchInput.on('input', function() {
            const inputValue = $(this).val().trim();

            // 更新调试信息
            updateDebugInfo(`输入内容: "${inputValue}"`);

            // 重置选中索引
            currentIndex = -1;

            // 如果输入为空，隐藏建议列表
            if (inputValue.length === 0) {
                $suggestionsList.hide();
                updateDebugInfo('输入为空，隐藏下拉框');
                return;
            }

            // // 如果输入长度小于2，可能不触发搜索（可根据需求调整）
            // if (inputValue.length < 2) {
            //     updateDebugInfo('输入长度不足，等待更多输入...');
            //     return;
            // }

            // 取消上一次未完成的请求
            if (lastRequest) {
                lastRequest.abort();
                updateDebugInfo('取消上一次请求');
            }

            // 显示加载状态
            $loadingIcon.show();
            updateDebugInfo('正在请求数据...');

            // 发送AJAX请求到后端接口
            lastRequest = $.ajax({
                url: 'http://localhost:8080/test/test',  // 你的后端API地址
                method: 'GET',
                data: {
                    singerName: inputValue  // 发送搜索关键词
                },
                dataType: 'json',
                timeout: 5000,  // 5秒超时

                success: function(response) {
                    $loadingIcon.hide();

                    singerName = response.map(item => item.singerName);

                    // 检查响应是否有效
                    if (response) {
                        updateDebugInfo(`从服务器获取到 ${singerName.length} 条结果`);
                        displaySuggestions(singerName, inputValue);
                        $suggestionsList.show();
                    } else {
                        updateDebugInfo('服务器返回格式不正确');
                        showErrorMessage('数据格式错误');
                    }
                },

                error: function(xhr, status, error) {
                    $loadingIcon.hide();

                    if (status !== 'abort') {  // 不是主动取消的请求
                        updateDebugInfo(`请求错误: ${status} - ${error}`);
                        showErrorMessage('获取数据失败，请重试');
                    } else {
                        updateDebugInfo('请求已取消');
                    }
                }
            });
        });

        // 显示建议列表
        function displaySuggestions(matches, inputValue) {
            // 清空现有列表
            $suggestionsList.empty();

            if (matches.length === 0) {
                $suggestionsList.append(`
                        <li class="no-results">没有找到匹配"${inputValue}"的结果</li>
                    `);
            } else {
                matches.forEach(item => {
                    // 这里假设item是字符串，如果是对象可以用item.name等属性
                    const itemText = typeof item === 'object' ? item.name : item;
                    const lowerItem = itemText.toLowerCase();
                    const lowerInput = inputValue.toLowerCase();
                    const index = lowerItem.indexOf(lowerInput);

                    let itemHtml;
                    if (index !== -1) {
                        const before = itemText.substring(0, index);
                        const match = itemText.substring(index, index + inputValue.length);
                        const after = itemText.substring(index + inputValue.length);
                        itemHtml = `${before}<span class="highlight">${match}</span>${after}`;
                    } else {
                        itemHtml = itemText;
                    }

                    const $li = $(`<li class="suggestion-item">${itemHtml}</li>`);

                    // 存储原始数据，方便后续使用
                    $li.data('originalData', item);

                    // 点击选择
                    $li.on('click', function() {
                        $searchInput.val(itemText);
                        $suggestionsList.hide();
                        // 可以在这里添加选择后的回调处理
                        handleSelection($(this).data('originalData'));
                    });

                    $suggestionsList.append($li);
                });
            }
        }

        // 处理选中项
        function handleSelection(data) {
            updateDebugInfo(`选中: ${JSON.stringify(data)}`);
            // 这里可以添加选中后的处理逻辑
            console.log('选中的数据:', data);
        }

        // 显示错误信息
        function showErrorMessage(message) {
            $suggestionsList.empty().append(`
                    <li class="error-message">${message}</li>
                `).show();
        }

        // 键盘事件处理
        $searchInput.on('keydown', function(e) {
            const $items = $suggestionsList.find('.suggestion-item');
            if ($items.length === 0) return;

            // 下箭头
            if (e.key === 'ArrowDown') {
                e.preventDefault();
                currentIndex = (currentIndex + 1) % $items.length;
                highlightSelection($items);
            }
            // 上箭头
            else if (e.key === 'ArrowUp') {
                e.preventDefault();
                currentIndex = (currentIndex - 1 + $items.length) % $items.length;
                highlightSelection($items);
            }
            // 回车键
            else if (e.key === 'Enter') {
                e.preventDefault();
                if (currentIndex >= 0) {
                    const $selected = $items.eq(currentIndex);
                    $searchInput.val($selected.text());
                    $suggestionsList.hide();
                    handleSelection($selected.data('originalData'));
                }
            }
            // ESC键
            else if (e.key === 'Escape') {
                $suggestionsList.hide();
            }
        });

        // 高亮选中项
        function highlightSelection($items) {
            $items.removeClass('active');
            $items.eq(currentIndex).addClass('active');

            // 滚动到可见区域
            const $activeItem = $items.eq(currentIndex);
            console.log($items.eq(currentIndex));


            if ($activeItem.length) {
                const listTop = $suggestionsList.scrollTop();
                const listHeight = $suggestionsList.height();
                const itemTop = $activeItem.position().top + listTop;
                const itemHeight = $activeItem.height();
                console.log(listTop);
                console.log(listHeight);
                console.log(itemTop);
                console.log(itemHeight);
                console.log($activeItem.position().top);

                // 如果项在可视区域上方
                if (itemTop < listTop) {
                    $suggestionsList.scrollTop(itemTop);
                }
                // 如果项在可视区域下方
                else if (itemTop + itemHeight > listTop + listHeight) {
                    $suggestionsList.scrollTop(itemTop + itemHeight - listHeight);
                }
            }
        }

        // 点击外部关闭下拉框
        $(document).on('click', function(e) {
            if (!$searchInput.is(e.target) && !$suggestionsList.is(e.target) &&
                !$suggestionsList.has(e.target).length) {
                $suggestionsList.hide();
            }
        });

        // 输入框聚焦时如果有内容则触发搜索
        $searchInput.on('focus', function() {
            if ($(this).val().trim().length >= 2) {
                $(this).trigger('input');
            }
        });

        // 更新调试信息
        function updateDebugInfo(text) {
            $debugInfo.text(`状态: ${text}`);
            console.log('调试:', text);
        }

        // 初始化
        updateDebugInfo('初始化完成，等待输入...');
    });
</script>
</body>
</html>
